//
//  ApplyViewController.m
//  MagazineShangejie
//
//  Created by wen on 15/9/20.
//  Copyright © 2015年 CnbizMedia. All rights reserved.
//

#import "ApplyViewController.h"
#import "Util.h"
@interface ApplyViewController (){
    NSInteger number;
}

@property (weak, nonatomic) IBOutlet UITextField *nameLabel;
@property (weak, nonatomic) IBOutlet UITextField *phoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *manNumberLabel;
@property (weak, nonatomic) IBOutlet UIView *manNumberView;
@property (weak, nonatomic) IBOutlet UIView *cooperationView;
@property (weak, nonatomic) IBOutlet UITextView *cooperationTextView;
@property (weak, nonatomic) IBOutlet UIView *moneyView;
@property (weak, nonatomic) IBOutlet UITextField *moneyText;

@end

@implementation ApplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.hidesBottomBarWhenPushed = YES;
    
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"tj"] forState:UIControlStateNormal];
    [button setFrame:CGRectMake(0, 0, 25, 25)];
    [button addTarget:self action:@selector(Submit) forControlEvents:UIControlEventTouchUpInside];
    ;
    [button.layer setCornerRadius:(button.frame.size.height / 2)];
    [button.layer setMasksToBounds:YES];
    UIBarButtonItem*rightItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem= rightItem;
    
    
    //2. 取出数据
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    number = [userDefault integerForKey:@"buttonTagNumber"];
    
    
    switch (number) {
        case 0:
            //论坛报名
            
            
            self.title = @"活动报名";
            _cooperationView.hidden = YES;
            _moneyView.hidden = YES;
            break;
            
        case 1:
            
            _cooperationView.hidden = YES;
            _moneyView.hidden = YES;
            self.title = @"游学报名";
            break;
            
        case 2:
//            咨询
            self.title = @"咨询";
            break;
            
        case 3:
            
            
            self.title = @"创投报名";
            break;
            
        default:
            break;
    }
    
    
    //指定本身为代理
    self.cooperationTextView.delegate = self;
    self.moneyText.delegate = self;
    //指定编辑时键盘的return键类型
    self.cooperationTextView.returnKeyType = UIReturnKeyNext;
    self.moneyText.returnKeyType = UIReturnKeyDefault;
    
    //注册键盘响应事件方法
//    [self.cooperationTextView addTarget:self action:@selector(nextOnKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.moneyText addTarget:self action:@selector(nextOnKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    //添加手势，点击屏幕其他区域关闭键盘的操作
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidenKeyboard)];
    gesture.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:gesture];

}

//提交数据
-(void)Submit{

    //2. 取出数据
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSDictionary *lunTanDic = [userDefault objectForKey:@"lunTanDic"];
    
    
    //创投报名
    if (number == 3) {
        
        ///意见建议
        [SVProgressHUD show];
        if (_cooperationTextView.text.length > 1 && _nameLabel.text.length > 1 && _phoneLabel.text.length == 11 && [_moneyText.text integerValue] > 0) {
            NSString *idString = [lunTanDic objectForKey:@"id"];
            NSString *catid    = [lunTanDic objectForKey:@"catid"];
            
            [[AppAPIClient sharedClient] POST:@"Apply/Add" parameters:@{@"id":idString,@"catid":catid,@"post_name":_nameLabel.text,@"post_mobile":_phoneLabel.text,} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                //                int code = [responseObject[@"code"] intValue];
                [SVProgressHUD showSuccessWithStatus:@"提交成功"];
                
                [self.navigationController popViewControllerAnimated:YES];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [SVProgressHUD showErrorWithStatus:LOADING_TEXT_ERROR];
                NSLog(@"Error:%@ => %@",error,operation.responseString);
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:@"请填写完资料,并确保信息准确..."];
        }
        
    }
    
    //活动，游学报名
    else{
        
        [SVProgressHUD show];
        if (_nameLabel.text.length > 1 && _phoneLabel.text.length ==11 && [_manNumberLabel.text integerValue] > 0) {
            
            NSString *idString = [lunTanDic objectForKey:@"id"];
            NSString *catid    = [lunTanDic objectForKey:@"catid"];
            
            [[AppAPIClient sharedClient] POST:@"Apply/Add" parameters:@{@"id":idString,@"catid":catid,@"post_name":_nameLabel.text,@"post_mobile":_phoneLabel.text,@"post_num":_manNumberLabel.text,} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                //                int code = [responseObject[@"code"] intValue];
                [SVProgressHUD showSuccessWithStatus:@"提交成功"];
                
                [self.navigationController popViewControllerAnimated:YES];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [SVProgressHUD showErrorWithStatus:LOADING_TEXT_ERROR];
                NSLog(@"Error:%@ => %@",error,operation.responseString);
            }];
        }
        else{
            [SVProgressHUD showErrorWithStatus:@"请填写完资料,并确保信息准确..."];
        }
    }
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)upManNumber:(id)sender {
    _manNumberLabel.text = [NSString stringWithFormat:@"%ld",[_manNumberLabel.text integerValue] + 1];
}

- (IBAction)downManNumber:(id)sender {
    if ([_manNumberLabel.text integerValue] == 0) {
        return;
    }
    
    else {
        _manNumberLabel.text = [NSString stringWithFormat:@"%ld",[_manNumberLabel.text integerValue] - 1];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [_nameLabel resignFirstResponder];
    [_phoneLabel resignFirstResponder];
    [_cooperationTextView resignFirstResponder];
    [_moneyText resignFirstResponder];
    
}

- (IBAction)submitButton:(id)sender {
    
    //2. 取出数据
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSDictionary *lunTanDic = [userDefault objectForKey:@"lunTanDic"];
    
    
    //创投报名
    if (number == 0) {

        ///意见建议
        [SVProgressHUD show];
        if (self.cooperationTextView.text.length>1 && _nameLabel.text.length > 1 && _phoneLabel.text.length !=11) {
            NSString *idString = [lunTanDic objectForKey:@"id"];
            NSString *catid    = [lunTanDic objectForKey:@"catid"];

            [[AppAPIClient sharedClient] POST:@"Apply/Add" parameters:@{@"id":idString,@"catid":catid,@"post_name":_nameLabel.text,@"post_mobile":_phoneLabel.text,} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                //                int code = [responseObject[@"code"] intValue];
                [SVProgressHUD showSuccessWithStatus:@"提交成功"];
                
                [self.navigationController popViewControllerAnimated:YES];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [SVProgressHUD showErrorWithStatus:LOADING_TEXT_ERROR];
                NSLog(@"Error:%@ => %@",error,operation.responseString);
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:@"请填写完资料,并确保信息准确..."];
        }

    }
    
    //活动，游学报名
    else{
        
        [SVProgressHUD show];
        if (_nameLabel.text.length > 1 && _phoneLabel.text.length !=11) {

        NSString *idString = [lunTanDic objectForKey:@"id"];
        NSString *catid    = [lunTanDic objectForKey:@"catid"];
        
        [[AppAPIClient sharedClient] POST:@"Apply/Add" parameters:@{@"id":idString,@"catid":catid,@"post_name":_nameLabel.text,@"post_mobile":_phoneLabel.text,@"post_num":_manNumberLabel.text,} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //                int code = [responseObject[@"code"] intValue];
            [SVProgressHUD showSuccessWithStatus:@"提交成功"];
            
            [self.navigationController popViewControllerAnimated:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:LOADING_TEXT_ERROR];
            NSLog(@"Error:%@ => %@",error,operation.responseString);
        }];
    }
        else{
            [SVProgressHUD showErrorWithStatus:@"请填写完资料,并确保信息准确..."];
        }
    }
    
    
}


#pragma mark - 键盘遮挡
//UITextField的协议方法，当开始编辑时监听
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    
    if ([textField isEqual:_moneyText]) {
        
    NSTimeInterval animationDuration=0.10f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    //上移30个单位，按实际情况设置
    CGRect rect=CGRectMake(0.0f,0.0f,width,height);
    self.view.frame=rect;
    [UIView commitAnimations];
    return YES;
    }
    return YES;

}

//恢复原始视图位置
-(void)resumeView
{
    NSTimeInterval animationDuration=0.10f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    //如果当前View是父视图，则Y为20个像素高度，如果当前View为其他View的子视图，则动态调节Y的高度
    float Y = 0.0f;
    CGRect rect=CGRectMake(0.0f,Y,width,height);
    self.view.frame=rect;
    [UIView commitAnimations];
}


//隐藏键盘的方法
-(void)hidenKeyboard
{
    [self.cooperationTextView resignFirstResponder];
    [self.moneyText resignFirstResponder];
    [self resumeView];
}

//点击键盘上的Return按钮响应的方法
-(IBAction)nextOnKeyboard:(UITextField *)sender
{
//    if (sender == self.cooperationTextView) {
//        [self.moneyText becomeFirstResponder];
//    }else if (sender == self.phoneLabel){
//        [self hidenKeyboard];
//    }
    
    [self hidenKeyboard];
}



//textview 挡住键盘
- (void)viewWillAppear:(BOOL)animated
{
    //注册通知,监听键盘出现
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(handleKeyboardDidShow:)
                                                name:UIKeyboardDidShowNotification
                                              object:nil];
    //注册通知，监听键盘消失事件
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(handleKeyboardDidHidden)
                                                name:UIKeyboardDidHideNotification
                                              object:nil];
    [super viewWillAppear:YES];
}

//监听事件
- (void)handleKeyboardDidShow:(NSNotification*)paramNotification
{
    //获取键盘高度
    NSValue *keyboardRectAsObject=[[paramNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect;
    [keyboardRectAsObject getValue:&keyboardRect];
    
//    _cooperationTextView.contentInset=UIEdgeInsetsMake(0, 0,keyboardRect.size.height, 0);
    
    NSTimeInterval animationDuration=0.10f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    //上移30个单位，按实际情况设置
//    CGRect rect=CGRectMake(0.0f,-80,width,height);
//    self.view.frame=rect;
    [UIView commitAnimations];
}

- (void)handleKeyboardDidHidden
{
    
    NSTimeInterval animationDuration=0.10f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    //如果当前View是父视图，则Y为20个像素高度，如果当前View为其他View的子视图，则动态调节Y的高度
    float Y = 0.0f;
    CGRect rect=CGRectMake(0.0f,Y,width,height);
    self.view.frame=rect;
    [UIView commitAnimations];
    
//    _cooperationTextView.contentInset=UIEdgeInsetsZero;
}
@end
